//plumb节点关系转树结构
import _ from "lodash"

type Node = {
	id: string,
	label: string
}
type Tnode = {
	id: string,
	label: string,
	children: Tnode[]
}
type Relation = {
	source: string,
	target: string
}
export function getByPath(tree:Tnode[], path:number[]){
	let tem:Tnode = tree[path[0]]
	for(let i=1;i<path.length;i++){
		tem = tem.children[path[i]]
	}
	return tem 
}
export function relation2tree(nodes:Node[], _relation:Relation[]):Object{
	let relation:Relation[] = _.cloneDeep(_relation)
	let tree:Tnode[] = []
	let path = new Map()
	let n_map = new Map()
	let p_node:Tnode
	let r_item:Relation|undefined
	for(let i=0;i<nodes.length;i++){
		n_map.set(nodes[i].id, Object.assign({},nodes[i],{children:[]})) 
	}
	while(relation.length>0){
		r_item = relation.shift()
		if(!r_item)break
		if(path.has(r_item.source)){
			let p_path = path.get(r_item.source)
			console.log("r_item.source", r_item.source);
			console.log("p_path ##", p_path);
			console.log("path ##$", path);
			console.log("r_item.target @@@", r_item.target);
			console.log("nmap $$$$$$$$", n_map);
			p_node = getByPath(tree, p_path)
			let c_node:Tnode = n_map.get(r_item.target)
			if(!c_node)continue
			n_map.delete(r_item.target)
			p_node.children.push(c_node)
			let c_index = p_node.children.length-1
			let c_path = _.clone(p_path)
			c_path.push(c_index)
			path.set(c_node.id, c_path)
		}else{
			let source_node = n_map.get(r_item.source)
			source_node.children = [n_map.get(r_item.target)]
			n_map.delete(r_item.source)
			n_map.delete(r_item.target)
			tree.push(source_node)
			path.set(r_item.source, [tree.length-1])
			path.set(r_item.target, [tree.length-1, 0])
		}
		r_item.source
	}
	for (let [key, node] of n_map) {
		tree.push(node)
	}
	
	return tree
}